package tools

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math"
	"net/http"
	"strconv"
)

func GetLocation(ip string) string {
	if ip == "127.0.0.1" || ip == "localhost" {
		return "内部IP"
	}
	resp, err := http.Get("https://restapi.amap.com/v3/ip?ip=" + ip + "&key=3fabc36c20379fbb9300c79b19d5d05e")
	if err != nil {
		panic(err)

	}
	defer resp.Body.Close()
	s, err := ioutil.ReadAll(resp.Body)
	fmt.Printf(string(s))

	m := make(map[string]string)

	err = json.Unmarshal(s, &m)
	if err != nil {
		fmt.Println("Umarshal failed:", err)
	}
	if m["province"] == "" {
		return "未知位置"
	}
	return m["province"] + "-" + m["city"]
}

//
func GetMemberLocation(lt, wt string, olt, owt string) string {
	if lt == "" || wt == "" {
		lt = "120.090564"
		wt = "30.344981"
	}
	if olt == "" || owt == "" {
		olt = "120.11638" // 经度
		owt = "30.2959"
	}
	lng, _ := strconv.ParseFloat(wt, 64)   // 纬度
	lat, _ := strconv.ParseFloat(lt, 64)   // 经度
	olng, _ := strconv.ParseFloat(owt, 64) // 纬度
	olat, _ := strconv.ParseFloat(olt, 64) // 经度

	//fmt.Printf("%f km", GeoDistance(120.090564, 30.344981, 120.11638, 30.2959, "K"))
	//纬度、经度 纬度、经度
	return fmt.Sprintf("%.2fkm", GeoDistance(lng, lat, olng, olat, "K"))
}

// 球面距离公式：https://baike.baidu.com/item/%E7%90%83%E9%9D%A2%E8%B7%9D%E7%A6%BB%E5%85%AC%E5%BC%8F/5374455?fr=aladdin
// GeoDistance 计算地理距离，依次为两个坐标的纬度、经度、单位（默认：英里，K => 公里，N => 海里）
func GeoDistance(lng1 float64, lat1 float64, lng2 float64, lat2 float64, unit ...string) float64 {
	const PI float64 = 3.141592653589793

	radlat1 := float64(PI * lat1 / 180)
	radlat2 := float64(PI * lat2 / 180)

	theta := float64(lng1 - lng2)
	radtheta := float64(PI * theta / 180)

	dist := math.Sin(radlat1)*math.Sin(radlat2) + math.Cos(radlat1)*math.Cos(radlat2)*math.Cos(radtheta)

	if dist > 1 {
		dist = 1
	}

	dist = math.Acos(dist)
	dist = dist * 180 / PI
	dist = dist * 60 * 1.1515

	if len(unit) > 0 {
		if unit[0] == "K" {
			dist = dist * 1.609344
		} else if unit[0] == "N" {
			dist = dist * 0.8684
		}
	}

	return dist
}
